package com.qianfeng.zhangwei.fruitday.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * @说 明：
 * @项目名称：Sz1504Adv
 * @包 名： com.qianfeng.zhangwei.fruitday.adapter
 * @类 名： AppFmPagerAdapter
 * @创 建人： zhangwei
 * @创建时间：2015-08-10 21:21
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class AppFmPagerAdapter extends PagerAdapter {

    private List<Fragment> fragments;

    private FragmentManager fragmentManager;


    public AppFmPagerAdapter(List<Fragment> fragments, FragmentManager fragmentManager) {
        this.fragments = fragments;
        this.fragmentManager = fragmentManager;
    }

    @Override
    public int getCount() {
        return fragments != null & !fragments.isEmpty() ? fragments.size() : 0;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return object == view;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = fragments.get(position);

        if (!fragment.isAdded()) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(fragment, fragment.getClass().getName());
            transaction.commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        View view = fragment.getView();
        if (view.getParent() == null) {
            container.addView(fragment.getView());
        }

        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(fragments.get(position).getView());
    }
}
